import React, { useState } from 'react';
import { withScriptjs, withGoogleMap, GoogleMap, Marker } from 'react-google-maps';
import { Spin, Row } from 'antd';
import { GOOGLE_KEY } from '@/pages/Attendance/Setting/config';

/**
 * 简单边界错误处理
 */
class ErrorBoundary extends React.Component {
    constructor(props) {
        super(props);
        this.state = { hasError: false };
    }

    componentDidCatch() {
        this.setState({ hasError: true });
    }

    render() {
        if (this.state.hasError) {
            return (
                <Row type="flex" justify="center" align="middle" style={{ height: '100%', fontSize: 20 }}>
                    地图加载错误，您可能无法访问google地图
                </Row>
            );
        }
        return this.props.children;
    }
}

const EnhanceGoogleMap = withScriptjs(
    withGoogleMap(({ defaultPosition }) => {
        const [position] = useState({ lat: Number(defaultPosition.latitude), lng: Number(defaultPosition.longitude) });

        return (
            <GoogleMap
                defaultZoom={8}
                center={position}
                options={{ streetViewControl: false, fullscreenControl: false, mapTypeControl: false }}
            >
                <Marker position={position} />
            </GoogleMap>
        );
    })
);

const Map = ({ defaultPosition, onChange, onSelect, visible }) => {
    const MAP_URL = `https://maps.googleapis.com/maps/api/js?key=${GOOGLE_KEY}&libraries=places`;
    const containerElement = <div style={{ height: '400px' }} />;
    const mapElement = <div style={{ height: '100%' }} />;
    const loadingComponent = (
        <Row type="flex" justify="center" align="middle" style={{ height: '100%' }}>
            <Spin />
        </Row>
    );

    return (
        <ErrorBoundary>
            <EnhanceGoogleMap
                visible={visible}
                defaultPosition={defaultPosition}
                onChange={onChange}
                onSelect={onSelect}
                googleMapURL={MAP_URL}
                loadingElement={loadingComponent}
                containerElement={containerElement}
                mapElement={mapElement}
            />
        </ErrorBoundary>
    );
};

export default Map;
